package com.sl.diary.activity;

import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.sl.diary.R;
import com.sl.diary.component.DatePickerDialog;
import com.sl.diary.db.TravelSQLiteHelper;
import com.sl.diary.model.TravelModel;
import com.sl.diary.util.Constant;
import com.sl.diary.util.Util;

public class A005_RegisterTravel extends BaseActivity {

	static final int SELECT_TRAVEL_ICON = 501;

	String travel_id = null;
	
	ImageView img_icon;
	TextView tv_departure_date, tv_end_date;
	EditText et_name, et_description;

	/** state of view */
	int state = Constant.TRAVEL_STATE_NEW;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.a005_register_travel);
		this.initView();
	}

	private void initView() {
		super.initNavigationBar();
		// icon
		img_icon = (ImageView) findViewById(R.id.img_register_travel_icon);
		img_icon.setOnClickListener(onClickIconImg);

		// name
		et_name = (EditText) findViewById(R.id.et_register_travel_name);

		// description
		et_description = (EditText) findViewById(R.id.et_register_travel_description);

		// departure date
		tv_departure_date = (TextView) findViewById(R.id.tv_register_travel_departure_date);
		ImageButton imgbtn_departure_date = (ImageButton) findViewById(R.id.imgbtn_register_travel_departure_date);
		imgbtn_departure_date.setOnClickListener(onClickDateBtn);

		// end date
		tv_end_date = (TextView) findViewById(R.id.tv_register_travel_end_date);
		ImageButton imgbtn_end_date = (ImageButton) findViewById(R.id.imgbtn_register_travel_end_date);
		imgbtn_end_date.setOnClickListener(onClickDateBtn);

		// save btn
		ImageButton btn_save = (ImageButton) findViewById(R.id.imgbtn_register_travel_save);
		btn_save.setOnClickListener(onClickSaveBtn);

		// set data for view
		Bundle extras = getIntent().getExtras();
		if (extras != null
				&& extras.getString(TravelSQLiteHelper.TRAVEL_ID) != null) {
			// change status type
			state = Constant.TRAVEL_STATE_EDIT;
			// set displayed date
			travel_id = extras.getString("travel_id");
			TravelModel travel = dbManager.getTravel(travel_id);
			et_name.setText(travel.getName());
			et_description.setText(travel.getDescription());
			// departure date
			Date departureDate = travel.getDeparture_date();
			tv_departure_date.setText(Util.convertDateToString(departureDate));
			tv_departure_date.setTag(departureDate);
			tv_departure_date.setVisibility(View.VISIBLE);
			// end date
			Date endDate = travel.getEnd_date();
			tv_end_date.setText(Util.convertDateToString(endDate));
			tv_end_date.setTag(endDate);
			tv_end_date.setVisibility(View.VISIBLE);
		}
	}

	/**
	 * implement event click on icon image
	 */
	OnClickListener onClickIconImg = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// show image gallery
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			startActivityForResult(i, SELECT_TRAVEL_ICON);
		}

	};

	/**
	 * implement event click on date button
	 */
	OnClickListener onClickDateBtn = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// show date picker
			showDatePickerDialog(v.getId(), Calendar.getInstance());
		}
	};
	/**
	 * implement event click on save button
	 */
	OnClickListener onClickSaveBtn = new OnClickListener() {

		@Override
		public void onClick(View v) {

			Boolean validationName = validationTravelName();
			Boolean validationDate = validationTravelDate();
			Boolean validationDescription = validationTravelDescription();

			if (validationName && validationDate && validationDescription) {
				String name = et_name.getText().toString();
				String description = et_description.getText().toString();
				Date departure_date = (Date) tv_departure_date.getTag();
				Date end_date = (Date) tv_end_date.getTag();
				String icon = (String) img_icon.getTag();

				TravelModel travelModel = new TravelModel(travel_id, name,
						description, departure_date, end_date, icon);

				if (state == Constant.TRAVEL_STATE_NEW) {
					travel_id = dbManager.addTravel(travelModel);
					
				} else if (state == Constant.TRAVEL_STATE_EDIT) {
					int indexRow = dbManager.updateTravel(travelModel);

					if (indexRow > -1) {
						Intent data = new Intent();
						data.putExtra(Constant.TRAVEL_STATE, Constant.TRAVEL_STATE_EDIT);		
						setResult(Constant.A005_CODE, data);
						finish();
					} else {
						Toast.makeText(
								A005_RegisterTravel.this,
								getString(R.string.message_register_travel_failed),
								Toast.LENGTH_LONG).show();
					}

				}
			}
		}
	};

	/**
	 * show date picker dialog
	 * 
	 * @param viewId
	 *            the id of departure/end date image button
	 * @param calendar
	 *            the {@link Calendar} current calendar
	 */
	private final void showDatePickerDialog(final int viewId,
			final Calendar calendar) {
		DatePickerDialog datePickerDialog = new DatePickerDialog(
				A005_RegisterTravel.this, R.style.DialogSlideAnim, calendar,
				null, new DatePickerDialog.DatePickerListner() {

					@Override
					public void OnDoneButton(Dialog dialog, Calendar c) {

						calendar.set(Calendar.YEAR, c.get(Calendar.YEAR));
						calendar.set(Calendar.MONTH, c.get(Calendar.MONTH));
						calendar.set(Calendar.DAY_OF_MONTH,
								c.get(Calendar.DAY_OF_MONTH));

						Date selectedDate = new Date(
								calendar.get(Calendar.YEAR) - 1900,
								calendar.get(Calendar.MONTH),
								calendar.get(Calendar.DAY_OF_MONTH));
						updateTvDateByViewId(viewId, selectedDate);
						dialog.dismiss();
					}

					@Override
					public void OnCancelButton(Dialog dialog) {
						dialog.dismiss();
					}
				});
		// show dialog
		datePickerDialog.show();
	}

	/**
	 * called in showDatePickerDialog to reset date string in departure/end date
	 * textview
	 * 
	 * @param viewId
	 *            the id of departure/end date image button
	 * @param date
	 *            the {@link Date} selected date
	 */
	private final void updateTvDateByViewId(int viewId, Date date) {
		if (viewId == R.id.imgbtn_register_travel_departure_date) {
			tv_departure_date.setTag(date);
			tv_departure_date.setText(Util.convertDateToString(date));

		} else if (viewId == R.id.imgbtn_register_travel_end_date) {
			tv_end_date.setTag(date);
			tv_end_date.setText(Util.convertDateToString(date));
		}
	}

	/**
	 * called when user selected image in gallery for travel's icon
	 */
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			if (requestCode == SELECT_TRAVEL_ICON) {
				Uri selectedImageUri = data.getData();
				img_icon.setImageURI(selectedImageUri);
				img_icon.setTag(selectedImageUri.getPath());
			}
		}
	}

	/**
	 * validation travel name
	 */
	private final boolean validationTravelName() {
		TextView tv_name_error = (TextView) findViewById(R.id.tv_register_travel_name_error);
		tv_name_error.setVisibility(View.VISIBLE);

		String name = et_name.getText().toString();
		String result = "";
		if (name.isEmpty()) {
			result = getString(R.string.error_message_validation_required);
		} else if (name.toString().length() < 1) {
			result = getString(R.string.error_message_validation_travel_name);
		} else {
			tv_name_error.setVisibility(View.GONE);
		}

		tv_name_error.setText(result);

		return result == "" ? true : false;
	}

	/**
	 * validation travel departure and end date
	 */
	private final boolean validationTravelDate() {
		TextView tv_date_error = (TextView) findViewById(R.id.tv_register_travel_date_error);
		String result = "";

		// departure date
		String departureDateStr = (String) tv_departure_date.getText();
		Date departureDate = new Date();

		if (departureDateStr.isEmpty()) {
			result = getString(R.string.error_message_validation_required);
		} else {
			departureDate = (Date) tv_departure_date.getTag();

			if (state == Constant.TRAVEL_STATE_NEW && departureDate.before(new Date())) {
				result = getString(R.string.error_message_validation_travel_from_date) + '\n';
			}
			// end date
			String endDateStr = (String) tv_end_date.getText();
			if (endDateStr.isEmpty()) {
				result += getString(R.string.error_message_validation_required);
			} else {
				Date endDate = (Date) tv_departure_date.getTag();
				if (endDate != null && endDate.before(departureDate)) {
					result += getString(R.string.error_message_validation_travel_to_date);
				}
			}
		}

		// hide/show date error text view
		if (result == "") {
			tv_date_error.setVisibility(View.GONE);
		} else {
			tv_date_error.setVisibility(View.VISIBLE);
			tv_date_error.setText(result);
		}

		return result == "" ? true : false;
	}

	/**
	 * validation travel description
	 */
	private final boolean validationTravelDescription() {
		TextView tv_description_error = (TextView) findViewById(R.id.tv_register_travel_description_error);
		tv_description_error.setVisibility(View.VISIBLE);

		String description = et_description.getText().toString();
		String result = "";
		if (description.isEmpty()) {
			result = getString(R.string.error_message_validation_required);
			tv_description_error.setText(result);
		} else {
			tv_description_error.setVisibility(View.GONE);
		}
		return result == "" ? true : false;
	}

}
